#include "zbGPIO.h"

u32 myFlag = enGPIO;

void initGPIO()
{
	GPIO_InitTypeDef GPIO_InitStructure;
	RCC_APB1PeriphClockCmd(ZGPIO_READ_CLK, ENABLE);
	RCC_APB1PeriphClockCmd(ZGPIO_WRITE_CLK, ENABLE);
	// reading only
	GPIO_InitStructure.GPIO_Pin =  ZGPIO_READ_PINS;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN ;
	GPIO_Init(ZGPIO_READ_PORT, &GPIO_InitStructure);

	// writing only
	GPIO_InitStructure.GPIO_Pin =  ZGPIO_WRITE_PINS;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN ;
	GPIO_Init(GPIOD, &GPIO_InitStructure);

	// write all to 0
	GPIO_Write(ZGPIO_WRITE_PORT, 0x00);
	GPIO_Write(ZGPIO_READ_PORT, 0x00);
}

void disableGPIO()
{
	GPIO_Write(ZGPIO_WRITE_PORT, 0x00);
	GPIO_Write(ZGPIO_READ_PORT, 0x00);
	RCC_APB2PeriphClockCmd(ZGPIO_READ_CLK, DISABLE);
	RCC_APB2PeriphClockCmd(ZGPIO_WRITE_CLK, DISABLE);
}

void updateGPIO()
{
	u8 cont = false;
	if(mygVars->enabled != newgVars->enabled)
	{
		// if we were off 
		if(!(mygVars->enabled & myFlag))
		{
			// and now we are on
			if(newgVars->enabled & myFlag)
			{
				initGPIO();
				// update to know that we are on now
				mygVars->enabled = (mygVars->enabled | myFlag);	
				cont = true;
			}
		}
		// if we were on
		if(mygVars->enabled & myFlag)
		{
			// and now we are off
			if(!(newgVars->enabled & myFlag))
			{
				disableGPIO();
				// clear bit so we are off next time
				mygVars->enabled = (mygVars->enabled & !myFlag);
			}
		}
	}
	
	// if we get to this point and we are disabled just ret
	if(!(mygVars->enabled & myFlag) && (cont == false))
	{
		return;
	}

	// if its actually a different value do something 
	if(mygVars->gpioWrite != newgVars->gpioWrite)
	{
		// update old value with new and update
		mygVars->gpioWrite = newgVars->gpioWrite;
		GPIO_Write( ZGPIO_WRITE_PORT, (u16)( mygVars->gpioWrite & 0xFFFF ) );
	}
	
	mygVars->gpioRead = ZGPIO_READ_DR;	
}

void testGPIO()
{
	printf("GPIO Test");
	newgVars->enabled = newgVars->enabled | myFlag;
	updateGPIO();
	debugChar = 'g';
	while(debugChar == 'g')
	{
		// test writing 0, reading whatever
		newgVars->gpioWrite = 0x00;
		updateGPIO();
		printf("GPIO OUT:0x%x GPIO IN:0x%x\r\n",mygVars->gpioWrite, mygVars->gpioRead );
		
		Delay(1000);

		// test writing all 1's reading whatever
		newgVars->gpioWrite = 0xFF;
		updateGPIO();
		printf("GPIO OUT:0x%x GPIO IN:0x%x\r\n",mygVars->gpioWrite, mygVars->gpioRead );

		Delay(1000);		
	}

}

//#define USRBTN1_H() 	GPIO_ReadInputDataBit(CTL_JMP1_PORT, CTL_JMP1_USER1)
//#define USRBTN2_H() 	GPIO_ReadInputDataBit(CTL_JMP2_PORT, CTL_JMP2_USER2)

